package com.easybuilder.core.rbac.config;

import com.easybuilder.core.rbac.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SysUserService userService;
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;


    // 指定密码的加密方式
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
//        return new PasswordEncoder() {
//            @Override
//            public String encode(CharSequence charSequence) {
//                return charSequence.toString();
//            }
//
//            @Override
//            public boolean matches(CharSequence charSequence, String s) {
//                return Objects.equals(charSequence.toString(), s);
//            }
//        };
    }

    // 配置用户及其对应的角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userService);
    }

    // 配置基于内存的 URL 访问权限
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭跨域
        http.csrf().disable();
        // 暂时放过所有请求
        http.authorizeRequests().anyRequest().permitAll();
//        // 配置请求规则
//        http.authorizeRequests() // 开启 HttpSecurity 配置
//                .antMatchers("/api/**").permitAll() // 请求/api/**不需要认证
//                .antMatchers("/login").permitAll() // 登陆请求不需要认证
//                .anyRequest().authenticated() // 用户访问其它URL都必须认证后访问（登录后访问）
//                // http.exceptionHandling().accessDeniedHandler(accessDeniedHandler); //未通过认证的处理，只有验证身份后才有效，对未登陆认证身份的请求无效
//                .and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); // 未通过认证的处理，对未登陆认证身份的请求生效，可返回自定义信息
    }

}